<script setup lang='ts' name="video-management-add">
import type { FormInstance } from 'element-plus'
import { videoUpdate } from '@fl/api/anjutong/house-video'
import { getHouseList } from '@fl/api/xf-api/label-manage'
import type { IVideoUpdate } from '@fl/api/anjutong/model/house-video-model'
import UpdatedOss from '@fl/components/upLoad-oss.vue'
import { ElButton, ElDialog, ElForm, ElFormItem, ElInput, ElMessage } from 'element-plus'
import { cloneDeep } from 'lodash-es'
import { nextTick, toRefs } from 'vue'

const props = withDefaults(defineProps<{
    data?: any
    modelValue: boolean
}>(), {
    data: () => {},
})

const emits = defineEmits(['update:modelValue', 'confirm', 'updatevideoloading', 'updateimgloading'])
const { data, modelValue } = toRefs(props)

const initialState = {
    videoLabel: '',
    videoCoverUrl: '',
    titleDescription: '',
    videoTitle: '',
    videoUrl: '',
    realestateId: '',
    orderFlag: 0,
}
const form = ref<IVideoUpdate>(cloneDeep(initialState))
const title = ref<string>('添加楼盘视频')
const formRef = ref()
const houseOptions = ref<any>([])

const rules = reactive<any>({
    titleDescription: [
        { message: '请输入说明', required: true, trigger: 'blur' },
    ],
    videoTitle: [
        { message: '请输入标题', required: true, trigger: 'blur' },
    ],
    videoUrl: [
        { message: '请上传', required: true, trigger: 'blur' },
    ],
    realestateId: [
        { message: '请选择', required: true },
    ],
    orderFlag: [
        { message: '请输入排序', required: true },
    ],
})

// 所有楼盘
const getHouseOptions = async() => {
    await new Promise(resolve => {
        getHouseList({ pageNum: 1, pageSize: 500, projectName: '' }).then((res) => {
            houseOptions.value = res.rows.reduce((pre: any, cur: any) => {
                cur.value = cur.projectId
                cur.label = cur.projectName
                pre.push(cur)
                return pre
            }, [])
            resolve('')
        })
    })
}
getHouseOptions()

async function doSave(formEl: FormInstance | undefined) {
    if (!formEl)
        return
    await formEl.validate((valid, fields) => {
        if (valid) {
            videoUpdate({ ...form.value }).then((res: any) => {
                if (res.code === 200) {
                    close(formEl)
                    emits('confirm')
                }
                else {
                    ElMessage({ message: res.msg, type: 'error' })
                }
            }).catch((err) => {
                const message = err?.response?.data?.message || err
                ElMessage({ message, type: 'error' })
            })
        }
        else { console.log('error submit!', fields) }
    })
}

function close(formEl?: FormInstance | undefined) {
    formEl && formEl.resetFields()
    emits('update:modelValue', false)
}

async function init(val: any) {
    await nextTick()
    if (val?.id) {
        title.value = '编辑楼盘视频'
        form.value = cloneDeep(val)
    }
    else {
        title.value = '添加楼盘视频'
        form.value = { ...initialState }
    }
}

function removeVideoTip() {
    formRef.value.clearValidate('videoUrl')
}
function removeImgTip() {
    formRef.value.clearValidate('videoCoverUrl')
}

defineExpose({
    removeVideoTip,
    removeImgTip
})

watch(data, (val: any) => {
    if (val)
        init(val)
}, {
    deep: true,
    immediate: true,
})
</script>

<template>
    <ElDialog v-model="modelValue"
              width="640"
              :close-on-click-modal="false"
              :title="title"
              @close="close"
              class="dialog"
    >
        <ElForm ref="formRef"
                :model="form"
                :rules="rules"
                label-width="auto"
                label-position="top"
                class="form"
        >

            <ElFormItem label="视频标题"
                        prop="videoTitle"
            >
                <ElInput show-word-limit maxlength="20" v-model="form.videoTitle" />
            </ElFormItem>

            <ElFormItem label="视频说明"
                        prop="titleDescription"
            >
                <ElInput show-word-limit maxlength="20" v-model="form.titleDescription" />
            </ElFormItem>

            <ElFormItem label="关联楼盘"
                        prop="realestateId"
            >
                <ElSelect v-model="form.realestateId"
                            placeholder="请选择"
                            size="large"
                            filterable
                >
                    <ElOption v-for="item in houseOptions"
                                :key="item.value"
                                :label="item.label"
                                :value="item.value"
                    />
                </ElSelect>
            </ElFormItem>

            <ElFormItem label="视频标签"
                        prop="videoLabel"
            >
                <ElInput v-model="form.videoLabel" show-word-limit maxlength="20" />
            </ElFormItem>

            <ElFormItem label="排序"
                        prop="orderFlag"
            >
                <el-input-number v-model="form.orderFlag" :min="1" :max="99999" />
            </ElFormItem>

            <ElRow>
                <ElCol :span="12">
                    <ElFormItem label="视频上传"
                                prop="videoUrl"
                    >
                        <UpdatedOss v-model="form.videoUrl"
                                    :is-video="true"
                                    :size="800"
                                    accept=".mp4,.wmv,.mov"
                                    @success="emits('updatevideoloading', false)"
                                    tips="建议视频时长2-5分钟，清晰度1080P"
                        />
                    </ElFormItem>
                </ElCol>
            </ElRow>

            <ElRow>
                <ElCol :span="12">
                    <ElFormItem label="视频封面"
                                prop="videoCoverUrl"
                    >
                        <UpdatedOss v-model="form.videoCoverUrl"
                                    accept=".png,.jpg,.jpeg"
                                    @success="emits('updateimgloading', false)"
                                    tips="建议封面尺寸510*540，分辨率不超过1280x1280"
                        />
                    </ElFormItem>
                </ElCol>
            </ElRow>

            <div class="footer">
                <ElButton @click="close(formRef)">
                    取消
                </ElButton>

                <ElButton type="primary"
                          @click="doSave(formRef)"
                >
                    确定
                </ElButton>
            </div>
        </ElForm>
    </ElDialog>
</template>

<style lang="scss" scoped>
:deep(.el-upload-list__item div) {
    width: 100%;
    video {
        width: 100%;
    }
}
.dialog {
    position: relative;
}
.form {
    height: 580px;
    width: 600px;
    overflow: auto;
    padding-bottom: 40px;
}
.footer {
    width: 90%;
    height: 60px;
    line-height: 60px;
    background: #fff;
    position: absolute;
    bottom: 0;
    text-align: center;

}
</style>